package com.example.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.mq.SeckillOrderTo;
import com.example.common.to.OrderTo;
import com.example.common.to.hasStockVo;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;
import com.example.common.utils.R;
import com.example.common.vo.MemberResponseVo;
import com.example.gulimall.order.constant.OrderConstant;
import com.example.gulimall.order.dao.OrderDao;
import com.example.gulimall.order.entity.OrderEntity;
import com.example.gulimall.order.entity.OrderItemEntity;
import com.example.gulimall.order.entity.PaymentInfoEntity;
import com.example.gulimall.order.enume.OrderStatusEnum;
import com.example.gulimall.order.feign.CartFeignService;
import com.example.gulimall.order.feign.MemberFeignService;
import com.example.gulimall.order.feign.ProductFeignService;
import com.example.gulimall.order.feign.WareFeignService;
import com.example.gulimall.order.interceptor.LoginUserInterceptor;
import com.example.gulimall.order.service.OrderItemService;
import com.example.gulimall.order.service.OrderService;
import com.example.gulimall.order.service.PaymentInfoService;
import com.example.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    StringRedisTemplate template;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    // 在这里 Feign调用异步线程运行时 ThreadLocal线程里的数据不能被新开的两个线程异步获取 所以die了
    // 所以为了保证正常 必须要对Feign进行设置
    // feign在多级调用会创建新的request 所以没登陆就被抓 所以需要加上请求拦截器
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        // 获取主线程数据

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 收获列表
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            // 给分线程设置数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberResponseVo.getId());
            System.out.println("会员服务运行成功");
            orderConfirmVo.setAddress(address);
        }, executor);


        // 购物车的购物项
        CompletableFuture<Void> orderFuture = CompletableFuture.runAsync(() -> {
            // 给分线程设置数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
            orderConfirmVo.setItems(currentCartItems);
            System.out.println("购物车服务运行成功");
        },executor).thenRunAsync(()->{
            // 这里还有调用微服务！！！
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.hasStock(collect);
            List<hasStockVo> data = r.getData(new TypeReference<List<hasStockVo>>() {});
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(hasStockVo::getSkuId, hasStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        },executor);


        // 查询用户积分
        Integer integration = memberResponseVo.getIntegration();
        orderConfirmVo.setIntegration(integration);
        // 订单总额

        // 准备防重复令牌
        String replace = UUID.randomUUID().toString().replace("-", "");
        template.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberResponseVo.getId(),replace,30, TimeUnit.MINUTES);
        orderConfirmVo.setToken(replace);

        CompletableFuture.allOf(orderFuture,addressFuture).get();
        // 应付金额
        return orderConfirmVo;
    }

    // 这个函数里包含分布式事务 需要好好思考一下怎么搞
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        confirmVoThreadLocal.set(vo);
        // 令牌的验证删除需要保证原子性 Lua脚本返回值 0表示失败 1表示成功
        // 令牌是来看是不是同一个订单 不是同一个订单就是错的！
        Long execute = template.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()), vo.getOrderToken());
        if (execute == 0L){
            responseVo.setCode(1);
            return responseVo;
        }
        responseVo.setCode(0);
        // 1.创建订单等信息
        OrderCreateTo order = createOrder();
        // System.out.println("创建出来的订单消息是"+order.toString());
        // 2.验价
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = vo.getPayPrice();
        if(Math.abs(payAmount.subtract(payPrice).doubleValue()) >= 0.1){
            responseVo.setCode(2);
            return responseVo;
        }
        // 3.保存订单
        saveOrder(order);

        // 4.库存锁定 只要有异常必须回滚
        // 订单号 所有订单项
        WareSkuLockVo lockVo = new WareSkuLockVo();
        lockVo.setOrderSn(order.getOrder().getOrderSn());
        List<OrderItemVo> itemVos = order.getOrderItems().stream().map(item -> {
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setSkuId(item.getSkuId());
            orderItemVo.setCount(item.getSkuQuantity());
            orderItemVo.setTitle(item.getSkuName());
            return orderItemVo;
        }).collect(Collectors.toList());
        lockVo.setLocks(itemVos);
        R r = wareFeignService.orderLockStock(lockVo);
        if(r.getCode() != 0)
            responseVo.setCode(3);
        else{
            // 订单锁定成功 接下来需要发送消息
            rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
            responseVo.setOrder(order.getOrder());
        }
        return responseVo;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        OrderEntity byId = this.getById(orderEntity.getId());
        if (byId.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            OrderEntity entity = new OrderEntity();
            entity.setId(orderEntity.getId());
            entity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(entity);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(byId,orderTo);
            //关单发送消息
            try{
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.order",orderTo);
            } catch (Exception e){
                // 出现错误的解决方法：
            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {

        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        payVo.setTotal_amount(order.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString());
        payVo.setOut_trade_no(orderSn);

        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = list.get(0);
        payVo.setSubject(itemEntity.getSkuName());
        payVo.setBody(itemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> orderSn = page.getRecords().stream().map(item -> {
            List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", item.getOrderSn()));
            item.setItemEntities(order_sn);
            return item;
        }).collect(Collectors.toList());

        page.setRecords(orderSn);

        return new PageUtils(page);
    }

    @Override
    public String handleRayResult(PayAsyncVo vo) {
        // 处理支付结果

        // 交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        //2.修改订单状态
        if(vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo to) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(to.getOrderSn());
        orderEntity.setMemberId(to.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setPayAmount(to.getSeckillPrice().multiply(new BigDecimal(to.getNum())));
        this.save(orderEntity);

        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(to.getOrderSn());
        itemEntity.setSkuId(to.getSkuId());
        itemEntity.setSkuPrice(to.getSeckillPrice());
        itemEntity.setRealAmount(to.getSeckillPrice().multiply(new BigDecimal(to.getNum())));
        itemEntity.setSkuQuantity(to.getNum());
        orderItemService.save(itemEntity);
    }

    private void saveOrder(OrderCreateTo order) {
        System.out.println("传进来的order实体是"+order.toString());
        // 保存订单数据
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }


    private OrderCreateTo createOrder(){
        OrderCreateTo createTo = new OrderCreateTo();

        // 生成订单ID
        // 填充运费信息
        String timeId = IdWorker.getTimeId();
        OrderEntity order = buildOrder(timeId);

        // 获取所有订单
        List<OrderItemEntity> orderItems = buildOrderItems(timeId);
        //System.out.println("此时的订单是:"+orderItems.toString());
        // 计算最后的价格
        createTo.setOrderItems(orderItems);
        computePrice(order,orderItems);
        createTo.setOrder(order);
        return createTo;
    }

    private void computePrice(OrderEntity order, List<OrderItemEntity> orderItems) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal( "0.0");

        for (OrderItemEntity orderItem : orderItems) {
            total = total.add(orderItem.getRealAmount());
            coupon = coupon.add(orderItem.getCouponAmount());
            integration = integration.add(orderItem.getIntegrationAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            gift = gift.add(new BigDecimal(orderItem.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(orderItem.getGiftGrowth().toString()));
        }
        // 订单价格
        order.setTotalAmount(total);
        // 快递已经算了 所以这里算总价
        order.setPayAmount(total.add(order.getFreightAmount()));
        order.setCouponAmount(coupon);
        order.setIntegrationAmount(integration);
        order.setPromotionAmount(promotion);
        // 积分
        order.setGrowth(growth.intValue());
        order.setIntegration(gift.intValue());
        // 删除状态
        order.setDeleteStatus(0);

    }

    public OrderEntity buildOrder(String timeId) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        OrderEntity order = new OrderEntity();
        order.setOrderSn(timeId);
        order.setMemberId(memberResponseVo.getId());
        order.setMemberUsername(memberResponseVo.getUsername());
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        R fare = wareFeignService.getFare(submitVo.getAddrId());
        FareVo fareVo = fare.getData(new TypeReference<FareVo>() {});
        order.setFreightAmount(fareVo.getFare());
        // 收货人信息
        order.setReceiverCity(fareVo.getAddress().getCity());
        order.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        order.setReceiverName(fareVo.getAddress().getName());
        order.setReceiverPhone(fareVo.getAddress().getPhone());
        order.setReceiverPostCode(fareVo.getAddress().getPostCode());
        order.setReceiverProvince(fareVo.getAddress().getProvince());
        order.setReceiverRegion(fareVo.getAddress().getRegion());

        //设置订单状态
        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        order.setAutoConfirmDay(7);

        return order;
    }

    // 构建订单项
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后一次确定订单价格
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
        if(currentCartItems != null && currentCartItems.size() > 0){
            List<OrderItemEntity> orderList = currentCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return orderList;
        }
        return null;
    }

    // 构建每一个订单项
    private OrderItemEntity buildOrderItem(OrderItemVo entity) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        // Spu信息
        R infoBySkuId = productFeignService.getSpuInfoBySkuId(entity.getSkuId());
        SpuInfoVo spuInfoVo = infoBySkuId.getData(new TypeReference<SpuInfoVo>() {});
        itemEntity.setSpuId(spuInfoVo.getId());
        itemEntity.setSpuName(spuInfoVo.getSpuName());
        itemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        itemEntity.setCategoryId(spuInfoVo.getCatalogId());
        // SkU信息
        itemEntity.setSkuId(entity.getSkuId());
        itemEntity.setSkuName(entity.getTitle());
        itemEntity.setSkuPic(entity.getImage());
        itemEntity.setSkuPrice(entity.getPrice());
        itemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(entity.getSkuAttr(),","));
        itemEntity.setSkuQuantity(entity.getCount());
        // 优惠信息 不做
        // 积分信息
        itemEntity.setGiftGrowth(entity.getPrice().multiply(new BigDecimal(entity.getCount())).intValue());
        itemEntity.setGiftIntegration(entity.getPrice().multiply(new BigDecimal(entity.getCount())).intValue());
        //计算优惠后的价格
        itemEntity.setPromotionAmount(new BigDecimal("0.0"));
        itemEntity.setCouponAmount(new BigDecimal("0.0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        itemEntity.setRealAmount(itemEntity.getSkuPrice()
                .multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()))
                .subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount()));
        return itemEntity;
    }
}